<template>
  <div class="detail">
    <el-card>
      <el-tabs>
        <el-tab-pane label="登录账号设置">
          <el-form ref="form" label-width="100px" :model="form" :rules="rules">
            <el-form-item label="姓名:" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码:" prop="password">
              <el-input v-model="form.password" type="password" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submit">更新</el-button>
              <el-button @click="exit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情" lazy>
          <component
            :is="'info'"
            :user-info="otherUserInfo"
            @updateUserInfo="updateUserInfo"
          />
        </el-tab-pane>
        <el-tab-pane label="岗位信息" lazy>
          <component :is="'job'" />
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { sysUser } from '@/api/user'
// 更新员工基本信息的接口
import { sysUserPut } from '@/api/employees'
export default {
  components: {
    info: () => import('./components/info.vue'),
    job: () => import('./components/job.vue')
  },
  data() {
    return {
      id: this.$route.params.id,
      userInfo: '',
      otherUserInfo: '',
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '必填', trigger: 'change' }],
        password: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 取消按钮
    exit() {
      this.$router.push('/employees')
    },
    // 获取个人信息
    async getData() {
      const res = await sysUser(this.id)
      // 让用户名进行回显
      this.form.username = res.data.username
      // 父组件的个人信息不能与子组件的个人信息相关联
      this.otherUserInfo = JSON.parse(JSON.stringify(res.data))
      // 个人信息存储起来
      this.userInfo = res.data
    },
    submit() {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          await sysUserPut({ ...this.userInfo, ...this.form })
          // 提示用户
          this.$message.success('用户信息更新成功')
        }
      })
    },
    // 子级传递过来的数据
    updateUserInfo(info) {
      this.form.username = info.username
      this.userInfo = JSON.parse(JSON.stringify(info))
    }
  }
}
</script>

<style lang="scss" scoped>
.detail {
  padding: 15px;
}
</style>
